import { ref } from 'vue';
import Taro from '@tarojs/taro';

/**
 * 加载状态 hook
 * @param initialState 初始状态，默认 false
 */
export function useLoading(initialState = false) {
  const loading = ref(initialState);

  // 设置加载状态
  const setLoading = (state: boolean) => {
    loading.value = state;
  };

  // 显示加载提示
  const showLoading = (title: string = '加载中...') => {
    Taro.showLoading({
      title,
      mask: true
    });
  };

  // 隐藏加载提示
  const hideLoading = () => {
    Taro.hideLoading();
  };

  // 包装异步函数，自动处理加载状态
  const withLoading = async <T>(fn: () => Promise<T>): Promise<T> => {
    try {
      setLoading(true);
      return await fn();
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    setLoading,
    showLoading,
    hideLoading,
    withLoading,
  };
}

/**
 * 使用示例：
 * const { loading, withLoading } = useLoading();
 * 
 * // 在异步函数中使用
 * const fetchData = async () => {
 *   const data = await withLoading(async () => {
 *     const response = await api.getData();
 *     return response.data;
 *   });
 *   console.log(data);
 * };
 * 
 * // 在模板中使用
 * <template>
 *   <div v-if="loading">加载中...</div>
 *   <div v-else>数据内容</div>
 * </template>
 */

/**
 * 分页加载状态 hook
 * @param initialPage 初始页码，默认 1
 * @param initialPageSize 初始每页条数，默认 10
 */
export function usePagination(initialPage = 1, initialPageSize = 10) {
  const current = ref(initialPage);
  const pageSize = ref(initialPageSize);
  const total = ref(0);
  const loading = ref(false);

  // 重置分页
  const reset = () => {
    current.value = initialPage;
    pageSize.value = initialPageSize;
    total.value = 0;
  };

  // 包装分页请求函数
  const withPagination = async <T>(
    fn: (page: number, pageSize: number) => Promise<{ list: T[]; total: number }>
  ): Promise<T[]> => {
    try {
      loading.value = true;
      const { list, total: totalCount } = await fn(current.value, pageSize.value);
      total.value = totalCount;
      return list;
    } finally {
      loading.value = false;
    }
  };

  return {
    current,
    pageSize,
    total,
    loading,
    reset,
    withPagination,
  };
}

/**
 * 使用示例：
 * const { current, pageSize, total, loading, withPagination } = usePagination();
 * 
 * // 在异步函数中使用
 * const fetchList = async () => {
 *   const list = await withPagination(async (page, size) => {
 *     const response = await api.getList({ page, pageSize: size });
 *     return {
 *       list: response.data.list,
 *       total: response.data.total,
 *     };
 *   });
 *   console.log(list);
 * };
 * 
 * // 在模板中使用
 * <template>
 *   <div v-if="loading">加载中...</div>
 *   <div v-else>列表内容</div>
 *   <nut-pagination
 *     v-model="current"
 *     :total="total"
 *     :page-size="pageSize"
 *     @change="fetchList"
 *   />
 * </template>
 */